var app = getApp();
var utils = require("../../utils/util.js");
Page({
  data: {
    //图片
    picList: [],
    //标签
    label: null,
    //分享心情
    describe: '',
  },
  onLoad: function(options) {
    //找到系统状态位置
    this.setData({
      statusBarHeight: app.globalData.systemInfo.statusBarHeight + 15
    })
    //读取缓存
    this.getCookie();
  },
  //图片加载错误清除缓存
  loadError: function() {
    this.setData({
      describe: '',
      label: null,
      picList: []
    })
    wx.removeStorage({
      key: 'imageTalk'
    })
  },

  //读取缓存
  getCookie: function() {
    var imageTalk = wx.getStorageSync("imageTalk");
    if (imageTalk != '') {
      var that = this;
      var imageTalk = JSON.parse(imageTalk);
      wx.showModal({
        title: '提示',
        content: '是否继续编写保存的草稿',
        cancelText: '重写',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#627096',
        success: function(e) {
          if (e.confirm) {
            var describe = imageTalk.describe;
            var label = imageTalk.label;
            var picList = imageTalk.picList;
            that.setData({
              describe: describe,
              label: label,
              picList: picList
            })
          }
          if (e.cancel) {
            that.loadError();
          }
        }
      })
    }
  },

  //添加照片
  addPic: function() {
    var that = this;
    wx.chooseImage({
      count: 6 - that.data.picList.length,
      success: function(r) {
        var list = [];
        for (var i of r.tempFiles) {
          var pic = {
            path: i.path,
            src: '',
            sequence: 0,
            width: 0,
            height: 0
          }
          list.push(pic);
        }
        //给一个URL属性.
        that.setData({
          picList: that.data.picList.concat(list)
        })
      },
    })
  },

  //加载图片
  loadPic: function(r) {
    var index = r.currentTarget.dataset.index;
    var picList = this.data.picList;
    var pic = picList[index];
    pic.width = r.detail.width;
    pic.height = r.detail.height;
    this.setData({
      picList: picList
    })
  },

  //删除照片
  dropPic: function(e) {
    var index = e.currentTarget.dataset.index;
    var picList = this.data.picList;
    picList.splice(index, 1);
    this.setData({
      picList: picList
    })
  },
  //选择话题
  selectLable: function() {
    wx.navigateTo({
      url: '/pages/label/label',
    })
  },
  //输入文字
  inputDescribe: function(e) {
    //当前输入数量
    var cursor = e.detail.cursor;
    var value = e.detail.value;
    //不能超过500
    if (cursor > 1000) {
      this.setData({
        describe: value.substring(0, 1000)
      })
    } else {
      this.setData({
        describe: value
      })
    }
  },
  //存草稿
  cookie: function() {
    var picList = this.data.picList;
    var label = this.data.label;
    var describe = this.data.describe;
    //图片 文字 标签 有一项填写则存稿
    if (picList.length != 0 || label != null || describe != '') {
      var imageTalk = {
        picList: picList,
        label: label,
        describe: describe
      }
      wx.setStorage({
        key: 'imageTalk',
        data: JSON.stringify(imageTalk),
      })
      wx.showToast({
        title: '已帮您成功存稿',
        icon: 'none',
        duration: 3000
      })
    }
  },
  //发布失败存草稿
  errCookie: function() {
    var picList = this.data.picList;
    var label = this.data.label;
    var describe = this.data.describe;
    var imageTalk = {
      picList: picList,
      label: label,
      describe: describe
    }
    wx.setStorage({
      key: 'imageTalk',
      data: JSON.stringify(imageTalk),
    })
    wx.showToast({
      title: '发布失败,已帮您自动存稿',
      icon: 'none',
      duration: 3000
    })
  },
  //获取policy
  getPolicy: function() {
    var picList = this.data.picList;
    var describe = this.data.describe;
    if (picList.length == 0) {
      wx.showToast({
        title: '您还没有上传图片呢.',
        icon: 'none',
        duration: 3000
      })
      return;
    }
    if (describe == '') {
      wx.showToast({
        title: '您还没有分享心情呢.',
        icon: 'none',
        duration: 3000
      })
      return;
    }
    var that = this;
    wx.showToast({
      title: '正在努力发布.',
      icon: 'loading',
      duration: 3000,
      mask: true
    })
    //延迟跳转
    var timeout = setTimeout(function() {
      that.rollback();
      clearTimeout(timeout);
    }, 3000)

    /* 从后端获取 Policy用于上传文件到阿里云oss */
    wx.request({
      url: app.globalData.requestUrl + 'getUploadFileOssPolicy',
      method: 'GET',
      data: {
        userId: app.globalData.user.id,
        type: 1
      },
      success: function(r) {
        if (r.data.code == 200) {
          that.upload(r.data.data, that.data.picList, 0);
        } else {
          that.errCookie();
        }
      },
      fail: function() {
        that.errCookie();
      }
    })
  },

  //上传图片
  upload: function(policyData, picList, index) {
    //图片上传完毕
    if (!(index < picList.length)) {
      //发布
      this.saveTalk();
      return;
    }
    var that = this;

    //生成名称
    var uuid = utils.getUUID();
    //获取类型
    var mimeType = utils.getMimeType(picList[index].path);
    var src = uuid + mimeType

    wx.uploadFile({
      url: policyData.host,
      filePath: picList[index].path,
      name: 'file',
      formData: {
        key: src,
        policy: policyData.policy,
        OSSAccessKeyId: policyData.accessid,
        success_action_status: '200',
        signature: policyData.signature
      },
      //成功要递归操作
      success: function(r) {
        //r.statusCode == 200
        if (r.statusCode == 200) {
          picList[index].src = src;
          picList[index].sequence = index + 1;
          //递归调用
          that.upload(policyData, picList, index + 1);
        } else {
          picList[index].src = null;
          picList[index].sequence = index + 1;
          //递归调用
          that.upload(policyData, picList, index + 1);
        }


      },
      fail: function() {
        that.errCookie();
      },
    })
  },
  //发布
  saveTalk: function() {
    var that = this;
    var picList = that.data.picList;
    for (var i = 0; i < picList.length; i++) {
      if (picList[i].src == null) {
        picList.splice(i, 1);
      }
    }
    wx.request({
      url: app.globalData.requestUrl + 'addTalk',
      method: 'POST',
      data: {
        userId: app.globalData.user.id,
        label: that.data.label == null ? '' : that.data.label.content,
        talkType: 0,
        talkDescribe: that.data.describe,
        resourceList: picList
      },
      success: function(r) {
        if (r.data.code == 200) {
          wx.removeStorage({
            key: 'imageTalk'
          })
        } else {
          that.errCookie();
        }
      },
      fail: function() {
        that.errCookie();
      }
    })
  },
  //返回下一个页面
  rollback: function() {
    //获取页面值栈
    var pages = getCurrentPages();
    wx.navigateBack({
      delta: 1
    })
  }
})